package me.wpf.search;

import me.wpf.core.HBaseTableUtil;
import me.wpf.model.HBaseRow;
import me.wpf.search.extractor.RowExtractor;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;

import java.io.IOException;
import java.io.Serializable;
import java.util.*;

/**
 * Description:hbase查询
 *
 * @author 王朋飞
 * @create 2019/8/13
 */
public class HBaseSearchHelper implements Serializable {

    /**
     * 单条语句查询
     *
     * @param tablename
     * @param get
     * @return
     * @throws IOException
     */
    public static HBaseRow search(String tablename, Get get) throws IOException {
        HBaseRow hBaseRow = null;
        List<HBaseRow> lists = search(tablename, Arrays.asList(get));
        if (!lists.isEmpty()) {
            hBaseRow = lists.get(0);
        }
        return hBaseRow;
    }


    /**
     * 多条语句查询
     *
     * @param tablename
     * @param gets
     * @return
     * @throws IOException
     */
    public static List<HBaseRow> search(String tablename, List<Get> gets) throws IOException {
        List<HBaseRow> data = new ArrayList<>();
        search(tablename, gets, data);
        return data;
    }


    /**
     * 实现具体的查询
     *
     * @param tablename
     * @param gets
     * @param data
     * @return
     * @throws IOException
     */
    private static void search(String tablename, List<Get> gets, List<HBaseRow> data) throws IOException {
        Table table = HBaseTableUtil.getTable(tablename);
        if (table != null) {
            Result[] results = table.get(gets);
            int n = 0;
            for (Result result : results) {
                if (!result.isEmpty()) {
                    HBaseRow rowData = RowExtractor.extractRowData(result);
                    if (rowData != null) {
                        data.add(rowData);
                    }
                }
            }
            HBaseTableUtil.close(table);
        } else {
            throw new IOException(" table:  " + tablename + " is not exists ..");
        }
    }


}
